// pages/secondhand/edit/edit.js
const app = getApp()

Page({
  data: {
    id: null,
    formData: {
      title: '',
      typeId: null,
      description: '',
      price: '',
      originalPrice: '',
      conditionStatus: '9成新',
      location: '',
      qq: '',
      phone: '',
      wechat: '',
      isUrgent: 0,
      freeShipping: 0,
      negotiable: 1,
      purchaseDate: '',
      usageDuration: ''
    },
    images: [],
    typeList: [],
    selectedTypeName: '', // 选中的类型名称
    conditionList: ['全新', '99新', '95新', '9成新', '8成新', '7成新', '其他'],
    selectedConditionIndex: 3,
    uploading: false,
    submitting: false,
    loading: true
  },

  onLoad(options) {
    if (options.id) {
      this.setData({ id: options.id })
      this.loadTypes()
      this.loadDetail()
    } else {
      wx.showToast({
        title: '商品ID不存在',
        icon: 'none'
      })
      setTimeout(() => {
        wx.navigateBack()
      }, 1500)
    }
  },

  // 加载商品类型
  async loadTypes() {
    try {
      const response = await app.utils.request({
        url: '/secondhand/types'
      })

      console.log('商品类型响应:', response)
      if (response && response.code === 200) {
        this.setData({
          typeList: response.data || []
        })
        console.log('商品类型列表:', response.data)
      }
    } catch (error) {
      console.error('加载类型失败:', error)
      wx.showToast({
        title: '加载类型失败',
        icon: 'none'
      })
    }
  },

  // 加载商品详情
  async loadDetail() {
    try {
      const response = await app.utils.request({
        url: `/secondhand/detail/${this.data.id}`
      })

      if (response && response.code === 200) {
        const detail = response.data

        // 解析图片
        let images = []
        if (detail.images) {
          try {
            images = JSON.parse(detail.images)
          } catch (e) {
            console.error('解析图片失败:', e)
          }
        }

        // 找到成色索引
        const conditionIndex = this.data.conditionList.indexOf(detail.conditionStatus)

        this.setData({
          formData: {
            title: detail.title || '',
            typeId: detail.typeId,
            description: detail.description || '',
            price: detail.price ? detail.price.toString() : '',
            originalPrice: detail.originalPrice ? detail.originalPrice.toString() : '',
            conditionStatus: detail.conditionStatus || '9成新',
            location: detail.location || '',
            qq: detail.qq || '',
            phone: detail.phone || '',
            wechat: detail.wechat || '',
            isUrgent: detail.isUrgent || 0,
            freeShipping: detail.freeShipping || 0,
            negotiable: detail.negotiable || 1,
            purchaseDate: detail.purchaseDate || '',
            usageDuration: detail.usageDuration ? detail.usageDuration.toString() : ''
          },
          images,
          selectedTypeName: detail.typeName || '',
          selectedConditionIndex: conditionIndex >= 0 ? conditionIndex : 3,
          loading: false
        })
      } else {
        wx.showToast({
          title: response.message || '加载失败',
          icon: 'none'
        })
        setTimeout(() => {
          wx.navigateBack()
        }, 1500)
      }
    } catch (error) {
      console.error('加载商品详情失败:', error)
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      })
      setTimeout(() => {
        wx.navigateBack()
      }, 1500)
    }
  },

  // 输入标题
  onTitleInput(e) {
    this.setData({
      'formData.title': e.detail.value
    })
  },

  // 选择类型
  onTypeChange(e) {
    const index = e.detail.value
    const selectedType = this.data.typeList[index]
    this.setData({
      'formData.typeId': selectedType.id,
      selectedTypeName: selectedType.typeName
    })
  },

  // 输入描述
  onDescriptionInput(e) {
    this.setData({
      'formData.description': e.detail.value
    })
  },

  // 输入价格
  onPriceInput(e) {
    this.setData({
      'formData.price': e.detail.value
    })
  },

  // 输入原价
  onOriginalPriceInput(e) {
    this.setData({
      'formData.originalPrice': e.detail.value
    })
  },

  // 选择成色
  onConditionChange(e) {
    const index = e.detail.value
    this.setData({
      selectedConditionIndex: index,
      'formData.conditionStatus': this.data.conditionList[index]
    })
  },

  // 输入地点
  onLocationInput(e) {
    this.setData({
      'formData.location': e.detail.value
    })
  },

  // 输入购买时间
  onPurchaseDateInput(e) {
    this.setData({
      'formData.purchaseDate': e.detail.value
    })
  },

  // 输入使用时长
  onUsageDurationInput(e) {
    this.setData({
      'formData.usageDuration': e.detail.value
    })
  },

  // 输入QQ
  onQQInput(e) {
    this.setData({
      'formData.qq': e.detail.value
    })
  },

  // 输入手机
  onPhoneInput(e) {
    this.setData({
      'formData.phone': e.detail.value
    })
  },

  // 输入微信
  onWechatInput(e) {
    this.setData({
      'formData.wechat': e.detail.value
    })
  },

  // 切换急售
  onUrgentChange(e) {
    this.setData({
      'formData.isUrgent': e.detail.value ? 1 : 0
    })
  },

  // 切换包邮
  onFreeShippingChange(e) {
    this.setData({
      'formData.freeShipping': e.detail.value ? 1 : 0
    })
  },

  // 切换议价
  onNegotiableChange(e) {
    this.setData({
      'formData.negotiable': e.detail.value ? 1 : 0
    })
  },

  // 选择图片
  async chooseImage() {
    if (this.data.images.length >= 9) {
      wx.showToast({
        title: '最多上传9张图片',
        icon: 'none'
      })
      return
    }

    try {
      const res = await wx.chooseImage({
        count: 9 - this.data.images.length,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera']
      })

      this.uploadImages(res.tempFilePaths)
    } catch (error) {
      console.error('选择图片失败:', error)
    }
  },

  // 上传图片
  async uploadImages(tempFilePaths) {
    this.setData({ uploading: true })

    try {
      const uploadPromises = tempFilePaths.map(filePath => {
        return new Promise((resolve, reject) => {
          wx.uploadFile({
            url: app.globalData.baseUrl + '/upload/file',
            filePath: filePath,
            name: 'file',
            header: {
              'Authorization': 'Bearer ' + wx.getStorageSync('token')
            },
            success: (res) => {
              try {
                const data = JSON.parse(res.data)
                console.log('图片上传响应:', data)
                if (data.code === 200 && data.data) {
                  // 后端返回的是 {url: '...', key: '...'}
                  resolve(data.data.url)
                } else {
                  reject(new Error(data.message || '上传失败'))
                }
              } catch (e) {
                console.error('解析上传响应失败:', e)
                reject(e)
              }
            },
            fail: reject
          })
        })
      })

      const uploadedUrls = await Promise.all(uploadPromises)
      this.setData({
        images: [...this.data.images, ...uploadedUrls],
        uploading: false
      })

      wx.showToast({
        title: '上传成功',
        icon: 'success'
      })
    } catch (error) {
      console.error('上传图片失败:', error)
      wx.showToast({
        title: '上传失败',
        icon: 'none'
      })
      this.setData({ uploading: false })
    }
  },

  // 预览图片
  previewImage(e) {
    const index = e.currentTarget.dataset.index
    wx.previewImage({
      current: this.data.images[index],
      urls: this.data.images
    })
  },

  // 删除图片
  deleteImage(e) {
    const index = e.currentTarget.dataset.index
    wx.showModal({
      title: '确认删除',
      content: '确定要删除这张图片吗？',
      success: (res) => {
        if (res.confirm) {
          const images = this.data.images.filter((_, i) => i !== index)
          this.setData({ images })
        }
      }
    })
  },

  // 表单验证
  validateForm() {
    const { title, typeId, price, description } = this.data.formData

    if (!title || title.trim() === '') {
      wx.showToast({
        title: '请输入商品标题',
        icon: 'none'
      })
      return false
    }

    if (!typeId) {
      wx.showToast({
        title: '请选择商品类型',
        icon: 'none'
      })
      return false
    }

    if (!price || parseFloat(price) <= 0) {
      wx.showToast({
        title: '请输入有效的价格',
        icon: 'none'
      })
      return false
    }

    if (!description || description.trim() === '') {
      wx.showToast({
        title: '请输入商品描述',
        icon: 'none'
      })
      return false
    }

    return true
  },

  // 提交更新
  async submitForm() {
    if (!this.validateForm()) {
      return
    }

    if (this.data.submitting) {
      return
    }

    this.setData({ submitting: true })

    try {
      const formData = {
        id: this.data.id,
        ...this.data.formData,
        images: JSON.stringify(this.data.images)
      }

      const response = await app.utils.request({
        url: '/secondhand/update',
        method: 'PUT',
        data: formData
      })

      if (response && response.code === 200) {
        wx.showToast({
          title: '更新成功',
          icon: 'success'
        })

        setTimeout(() => {
          wx.navigateBack()
        }, 1500)
      } else {
        wx.showToast({
          title: response.message || '更新失败',
          icon: 'none'
        })
        this.setData({ submitting: false })
      }
    } catch (error) {
      console.error('更新失败:', error)
      wx.showToast({
        title: '更新失败',
        icon: 'none'
      })
      this.setData({ submitting: false })
    }
  },

  // 取消编辑
  cancelEdit() {
    wx.showModal({
      title: '确认取消',
      content: '确定要放弃修改吗？',
      success: (res) => {
        if (res.confirm) {
          wx.navigateBack()
        }
      }
    })
  }
})

